﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>角色管理</title>
    <link href="//unpkg.com/layui@2.11.2/dist/css/layui.css" rel="stylesheet">
</head>
<body>
    <!-- 搜索表单 -->
    <div class="layui-form layui-form-pane" style="margin: 15px;">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">角色名称</label>
                <div class="layui-input-inline">
                    <input type="text" name="roleName" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <button class="layui-btn" lay-submit lay-filter="searchForm">
                    <i class="layui-icon layui-icon-search"></i> 搜索
                </button>
                <button class="layui-btn layui-btn-normal" id="btnAdd">
                    <i class="layui-icon layui-icon-add-1"></i> 添加角色
                </button>
            </div>
        </div>
    </div>

    <!-- 数据表格 -->
    <table id="roleTable" lay-filter="roleTable"></table>

    <!-- 表格工具栏模板 -->
    <script type="text/html" id="tableToolbar">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="edit">
                <i class="layui-icon layui-icon-edit"></i> 编辑
            </button>
            <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">
                <i class="layui-icon layui-icon-delete"></i> 删除
            </button>
        </div>
    </script>

    <!-- 添加/编辑表单模板 -->
    <script type="text/html" id="editFormTpl">
        <form class="layui-form" id="editForm" lay-filter="editForm" style="margin: 20px;">
            <input type="hidden" name="id" id="editId">
            <div class="layui-form-item">
                <label class="layui-form-label">角色名称</label>
                <div class="layui-input-block">
                    <input type="text" name="RoleName" id="editRoleName" required lay-verify="required" 
                           placeholder="请输入角色名称" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item" style="text-align: center;">
                <button class="layui-btn" type="button" id="btnSubmit">
                    <i class="layui-icon layui-icon-ok"></i> 确定
                </button>
                <button class="layui-btn layui-btn-primary" type="button" id="btnCancel">
                    <i class="layui-icon layui-icon-close"></i> 取消
                </button>
            </div>
        </form>
    </script>

    <script src="//unpkg.com/layui@2.11.2/dist/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'layer'], function(){
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;

            // 初始化表格
            table.render({
                elem: '#roleTable',
                url: '/RBAC/GetRoles',
                method: 'get',
                page: true,
                limit: 10,
                limits: [10, 20, 30, 50],
                toolbar: true,
                defaultToolbar: ['filter', 'print', 'exports'],
                cols: [[
                    {field: 'id', title: 'ID', width: 80, sort: true},
                    {field: 'roleName', title: '角色名称', width: 200},
                    {title: '操作', toolbar: '#tableToolbar', width: 200}
                ]],
                parseData: function(res){
                    console.log('开始解析服务器返回的数据');
                    console.log('原始响应数据：', JSON.stringify(res));
                    
                    // 检查响应数据的结构
                    if (!res) {
                        console.error('响应数据为空');
                        return {
                            code: 1,
                            msg: "响应数据为空",
                            count: 0,
                            data: []
                        };
                    }

                    // 检查数据格式
                    var result = {
                        "code": res.code !== undefined ? res.code : 0,
                        "msg": res.msg || "",
                        "count": res.count !== undefined ? res.count : 0,
                        "data": res.data || []
                    };

                    console.log('解析后的数据：', JSON.stringify(result));
                    return result;
                },
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                where: {
                    roleName: '' // 添加默认的搜索参数
                },
                response: {
                    statusCode: 0
                },
                done: function(res, curr, count) {
                    console.log('表格渲染完成');
                    console.log('当前页：', curr);
                    console.log('总数：', count);
                    console.log('渲染数据：', JSON.stringify(res));
                    
                    if(res.data && res.data.length === 0) {
                        if(res.count > 0 && curr > 1) {
                            console.log('当前页无数据，返回上一页');
                            table.reload('roleTable', {
                                page: {
                                    curr: curr - 1
                                }
                            });
                        } else {
                            console.log('无数据可显示');
                            layer.msg('暂无数据', {icon: 0});
                        }
                    }
                },
                error: function(xhr, status, error) {
                    console.error('请求发生错误');
                    console.error('状态码：', xhr.status);
                    console.error('状态文本：', status);
                    console.error('错误信息：', error);
                    console.error('响应文本：', xhr.responseText);
                    
                    try {
                        var errorMsg = "获取数据失败";
                        if (xhr.responseText) {
                            var resp = JSON.parse(xhr.responseText);
                            console.log('解析错误响应：', resp);
                            if (resp && resp.msg) {
                                errorMsg = resp.msg;
                            }
                        }
                        layer.msg(errorMsg, {icon: 2});
                    } catch(e) {
                        console.error('解析错误响应失败：', e);
                        layer.msg('获取数据失败', {icon: 2});
                    }
                }
            });

            // 搜索表单提交
            form.on('submit(searchForm)', function(data){
                table.reload('roleTable', {
                    where: {
                        roleName: data.field.roleName || ''
                    },
                    page: {
                        curr: 1
                    }
                });
                return false;
            });

            // 添加角色按钮点击事件
            $('#btnAdd').on('click', function(){
                showEditForm();
            });

            // 表格工具栏事件
            table.on('tool(roleTable)', function(obj){
                var data = obj.data;
                if(obj.event === 'edit'){
                    showEditForm(data);
                } else if(obj.event === 'del'){
                    layer.confirm('确定要删除该角色吗？', function(index){
                        var loadIndex = layer.load(1, {shade: [0.3, '#000']});
                        
                        var formData = new FormData();
                        formData.append('id', data.id);
                        
                        $.ajax({
                            url: '/RBAC/DeleteRole',
                            type: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                            success: function(res){
                                layer.close(loadIndex);
                                
                                if(res && res.success){
                                    layer.msg(res.message || '删除成功', {icon: 1});
                                    // 重新加载表格数据
                                    table.reload('roleTable');
                                } else {
                                    layer.msg(res && res.message ? res.message : '删除失败', {icon: 2});
                                }
                            },
                            error: function(xhr, status, error){
                                layer.close(loadIndex);
                                
                                console.error('错误信息：', xhr.responseText);
                                try {
                                    var errorRes = JSON.parse(xhr.responseText);
                                    if (errorRes && errorRes.message) {
                                        layer.msg(errorRes.message, {icon: 2});
                                        return;
                                    }
                                } catch (e) {}
                                layer.msg('请求失败：' + error, {icon: 2});
                            }
                        });
                        layer.close(index);
                    });
                }
            });

            // 显示编辑表单
            function showEditForm(data){
                layer.open({
                    type: 1,
                    title: data ? '编辑角色' : '添加角色',
                    area: ['500px', '300px'],
                    content: $('#editFormTpl').html(),
                    success: function(){
                        form.render();
                        if(data){
                            $('#editId').val(data.id);
                            $('#editRoleName').val(data.roleName);
                        }
                    }
                });
            }

            // 取消按钮点击事件
            $(document).on('click', '#btnCancel', function(){
                layer.closeAll();
            });

            // 提交按钮点击事件
            $(document).on('click', '#btnSubmit', function(){
                var id = $('#editId').val();
                var roleName = $('#editRoleName').val();
                
                if(!roleName){
                    layer.msg('角色名称不能为空', {icon: 2});
                    return;
                }
                
                // 禁用按钮防止重复提交
                var $btn = $(this);
                $btn.prop('disabled', true).addClass('layui-btn-disabled');
                var loadIndex = layer.load(1, {shade: [0.3, '#000']});
                
                var formData = new FormData();
                formData.append('RoleName', roleName);
                if(id) {
                    formData.append('id', id);
                }
                
                var isCreate = !id;
                $.ajax({
                    url: id ? '/RBAC/UpdateRole' : '/RBAC/CreateRole',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res){
                        layer.close(loadIndex);
                        $btn.prop('disabled', false).removeClass('layui-btn-disabled');
                        
                        if(res && res.success){
                            layer.closeAll('page');
                            layer.msg(res.message || '操作成功', {icon: 1});
                            // 重新加载表格数据
                            table.reload('roleTable', {
                                page: { curr: 1 }
                            });
                        } else {
                            layer.msg(res && res.message ? res.message : '操作失败', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error){
                        layer.close(loadIndex);
                        $btn.prop('disabled', false).removeClass('layui-btn-disabled');
                        
                        console.error('错误信息：', xhr.responseText);
                        try {
                            var errorRes = JSON.parse(xhr.responseText);
                            if (errorRes && errorRes.message) {
                                layer.msg(errorRes.message, {icon: 2});
                                return;
                            }
                        } catch (e) {}
                        layer.msg('请求失败：' + error, {icon: 2});
                    }
                });
            });
        });
    </script>
</body>
</html>